package cn.hpclub.server.controller.admin;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.model.Themes;
import cn.hpclub.server.service.ThemesService;
import cn.hpclub.server.util.ResultCode;
import cn.hpclub.server.validator.admin.ThemesValidator;
// import cn.hpclub.server.validator.admin.ThemesValidator;

// @API("/CmccbussinessServer/Dzg")
// @API("/CmccbussinessServer/:appName")
// @ControllerBind(controllerKey="/themes")
public class ThemesController extends BaseAdminController<Themes>{
    private static final Logger logger              = LoggerFactory.getLogger(ThemesController.class);
    private static final String HTML_LIST           = "/admin/themes.tpl";
    private static final String HTML_AUTH_LIST      = "/admin/themes_auth_list.tpl";
    private static final String URL_LIST            = "/themes/list";
    private static final String HTML_ADD            = "/admin/themes_input.tpl";
    private static final String KEYWORDS            = "keywords";
    private static final String THEMES_NAME         = "themes.name";
    private static final String THEMES_SORT         = "themes.sort";
    private static final String THEMES_ENABLED      = "themes.enabled";
    private static final String THEMES_LINK_URL     = "themes.link_url";
    private static final String THEMES_IMG_URL      = "themes.img_url";
    private static final String THEMES_DESC         = "themes.remark";
    private static final String THEMES_ID           = "themes.id";
    private static final String THEMES_IS_SECTION   = "themes.is_section";
    private static final String THEMES_SECTION_DESC = "themes.section_desc";

    private static final String IS_CHECKED          = "isChecked";
    private static final String SID                 = "sid";
    private static final String THEMES              = "themes";
    private static final String TYPE_TEXT           = "type_text";
    private static final String IS_SECTION          = "isSection";

    /**
     * @Title: list
     * @Description:主题列表界面，包含搜索和分页
     */
    @SuppressWarnings("static-access")
    public void list(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        // type=5为政企专区，如果以后5-10都是政企专区，则需要修改type条件
        findByPageForSearch("select *,(case when type=0 then '外链' when type=1 then '开户' when type=2 then '充值缴费' when type=3 then '实名补登记' when type=5 then '政企专区' end) as type_text ",
                            ThemesService.service.getSqlExceptSelect(searchInfo));
        setAttrs(searchInfo);
        render(HTML_LIST);
    }

    @SuppressWarnings("static-access")
    public void authList(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        // type=5为政企专区，如果以后5-10都是政企专区，则需要修改type条件
        findByPageForSearch("select *,(case when type=0 then '外链' when type=1 then '开户' when type=2 then '充值缴费' when type=3 then '实名补登记' when type=5 then '政企专区' end) as type_text ",
                            ThemesService.service.getSqlExceptSelect(searchInfo));
        setAttrs(searchInfo);
        render(HTML_AUTH_LIST);
    }

    @Override
    public void delete(){

        String[] ids = getParaValues(Constant.IDS);
        ResultCode result = ThemesService.service.deleteThemes(ids);

        if(result == ResultCode.SUCCESS){
            ajaxJsonSuccessMessage(Constant.Msg.DEL_DONE);
        } else if(result == ResultCode.PARAM_ERROR){
            ajaxJsonErrorMessage(Constant.Msg.DEL_FAILED);
        } else if(result == ResultCode.FAILED){
            ajaxJsonErrorMessage(Constant.Msg.DEL_FAILED);
        }
    }

    /**
     * @Title: save
     * @Description:新增保存
     */
    @Before({ Tx.class, ThemesValidator.class })
    public void save(){
        setThemes();
    }

    /**
     * @Title: update
     * @Description:编辑保存
     */
    @Before({ Tx.class, ThemesValidator.class })
    public void update(){
        setThemes();
    }

    private void setThemes(){
        Themes themes = getModel(Themes.class);
        themes.set(Themes.NAME, getPara(THEMES_NAME));
        themes.set(Themes.SORT, getPara(THEMES_SORT));
        themes.set(Themes.ENABLED, getPara(THEMES_ENABLED));
        themes.set(Themes.LINK_URL, getPara(THEMES_LINK_URL));
        themes.set(Themes.IMG_URL, getPara(THEMES_IMG_URL));
        themes.set(Themes.DESC, getPara(THEMES_DESC));
        themes.set(Themes.IS_SECTION, getPara(THEMES_IS_SECTION));
        themes.set(Themes.SECTION_DESC, getPara(THEMES_SECTION_DESC));
        themes.set(Themes.CREATE_TIME, new Date());

        String id = getPara(THEMES_ID);
        if(StrKit.notBlank(id)){
            // 修改主题时，不修改主题的type
            themes.set(Themes.ID, id);
            themes.update();
        } else{
            // 新增一条，默认为0.如果非0，需要手动去修改themes对应条目的type字段。
            themes.set(Themes.TYPE, 0);
            themes.save();
        }

        redirect(URL_LIST);
    }

    /**
     * 新增
     */
    public void add(){
        page();
    }

    /**
     * 编辑
     */
    public void edit(){
        page();
    }

    public void addAuthorizationOrg(){
        int orgID = Integer.parseInt(getPara("orgID"));
        int themesID = Integer.parseInt(getPara("themesId"));
        List<Record> list = Db.find("SELECT id FROM themes_organization WHERE org_id=? AND themes_id=?", orgID,
                                    themesID);
        if(list.isEmpty()){
            Db.update("INSERT INTO themes_organization(themes_id, org_id,updated_time) values(?,?,?)", themesID, orgID,
                      new Date());
        } else{
            Db.update("UPDATE themes_organization SET updated_time=? WHERE org_id=? AND themes_id=?", new Date(), orgID,
                      themesID);
        }
        keepPara("themesId");
        JSONObject obj = new JSONObject();
        obj.put("result", "OK");
        renderText(obj.toString());
    }

    public void addAuthorizationCity(){
        // int orgID = Integer.parseInt(getPara("orgID"));
        String[] ids = getParaValues("idsCity");
        int themesID = Integer.parseInt(getPara("themesId"));
        // System.out.println("themesID:" + themesID);
        // System.out.println("ids:" + ids);

        for(int i = 0; i < ids.length; i++){
            // System.out.println("ids i:" + ids[i]);
            List<Record> list = Db.find("SELECT id FROM themes_city WHERE city_org_id=? AND themes_id=?", ids[i],
                                        themesID);
            if(list.isEmpty()){
                Db.update("INSERT INTO themes_city(themes_id, city_org_id,updated_time) values(?,?,?)", themesID,
                          ids[i], new Date());
            } else{
                Db.update("UPDATE themes_city SET updated_time=? WHERE city_org_id=? AND themes_id=?", new Date(),
                          ids[i], themesID);
            }
        }

        keepPara("themesId");
        JSONObject obj = new JSONObject();
        obj.put("result", "OK");
        renderText(obj.toString());
    }

    public void deleteAuthorizationOrg(){
        String[] ids = getParaValues(Constant.IDS);
        ResultCode result = ThemesService.service.deleteAuthorizationOrg(ids);

        if(result == ResultCode.SUCCESS){
            ajaxJsonSuccessMessage(Constant.Msg.DEL_DONE);
        } else if(result == ResultCode.PARAM_ERROR){
            ajaxJsonErrorMessage(Constant.Msg.DEL_FAILED);
        } else if(result == ResultCode.FAILED){
            ajaxJsonErrorMessage(Constant.Msg.DEL_FAILED);
        }
    }

    public void deleteAuthorizationCity(){
        String[] ids = getParaValues("idsCity");
        ResultCode result = ThemesService.service.deleteAuthorizationCity(ids);

        if(result == ResultCode.SUCCESS){
            ajaxJsonSuccessMessage(Constant.Msg.DEL_DONE);
        } else if(result == ResultCode.PARAM_ERROR){
            ajaxJsonErrorMessage(Constant.Msg.DEL_FAILED);
        } else if(result == ResultCode.FAILED){
            ajaxJsonErrorMessage(Constant.Msg.DEL_FAILED);
        }
    }

    public void deleteAllAuthorizationMember(){
        String themesId = getPara("themesId");
        ResultCode result = ThemesService.service.deleteAllAuthorizationMember(themesId);

        if(result == ResultCode.SUCCESS){
            ajaxJsonSuccessMessage(Constant.Msg.DEL_DONE);
        } else if(result == ResultCode.PARAM_ERROR){
            ajaxJsonErrorMessage(Constant.Msg.DEL_FAILED);
        } else if(result == ResultCode.FAILED){
            ajaxJsonErrorMessage(Constant.Msg.DEL_FAILED);
        }
    }

    public void addAuthorizationMember(){
        int orgID = Integer.parseInt(getPara("memberId"));
        int themesID = Integer.parseInt(getPara("themesId"));
        List<Record> list = Db.find("SELECT id FROM themes_member WHERE member_id=? AND themes_id=?", orgID, themesID);
        if(list.isEmpty()){
            Db.update("INSERT INTO themes_member(themes_id, member_id,updated_time) values(?,?,?)", themesID, orgID,
                      new Date());
        } else{
            Db.update("UPDATE themes_member SET updated_time=? WHERE member_id=? AND themes_id=?", new Date(), orgID,
                      themesID);
        }
        keepPara("themesId");
        JSONObject obj = new JSONObject();
        obj.put("result", "OK");
        renderText(obj.toString());
    }

    public void deleteAuthorizationMember(){
        String[] ids = getParaValues("idsMember");
        ResultCode result = ThemesService.service.deleteAuthorizationMember(ids);

        if(result == ResultCode.SUCCESS){
            ajaxJsonSuccessMessage(Constant.Msg.DEL_DONE);
        } else if(result == ResultCode.PARAM_ERROR){
            ajaxJsonErrorMessage(Constant.Msg.DEL_FAILED);
        } else if(result == ResultCode.FAILED){
            ajaxJsonErrorMessage(Constant.Msg.DEL_FAILED);
        }
    }

    /**
     * @Title: page
     * @Description:跳到新增编辑页面
     */
    private void page(){
        String sid = getSession().getId();
        String id = getPara(THEMES_ID);
        if(StrKit.notBlank(id)){
            Themes themes = Themes.dao.findById(id);
            setAttr(IS_CHECKED, themes.get(Themes.ENABLED));
            setAttr(IS_SECTION, themes.get(Themes.IS_SECTION));
            setAttr(THEMES, themes);
            // 编辑页面，显示主题类型，但不支持修改。编辑页面修改主题不会修改主题的类型。
            setAttr(TYPE_TEXT, getTypeText(themes.getInt(Themes.TYPE)));
        } else{
            setAttr(IS_CHECKED, 1);
            setAttr(IS_SECTION, 0);
            // 新增页面，显示主题类型为外链，保存时，默认为外链形式。如果需要修改，需联系管理员在后台进行修改。
            setAttr(TYPE_TEXT, "外链");
        }
        setAttr(SID, sid);
        render(HTML_ADD);
    }

    public void authorize(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        String id = getPara("themesId");
        setAttr("themesId", id);
        Themes themes = Themes.dao.findById(id);
        setAttr("name", themes.getStr("name"));

        String searchType = getPara("searchType", "city");
        setAttr("searchType", searchType);
        findByPageForSearch4City("SELECT themes_city.id, themes.name, org.DisplayName, org.NumCode ",
                                 ThemesService.service.getSqlAuthorizationCityExceptSelect(id, searchInfo));

        findByPageForSearch("SELECT themes_org.id, themes.name, org.DisplayName, org.NumCode ",
                            ThemesService.service.getSqlAuthorizationOrgExceptSelect(id, searchInfo));

        findByPageForSearch4Member("SELECT themes_member.id, name, mobile, emp_code ",
                                   ThemesService.service.getSqlAuthorizationMemberExceptSelect(id, searchInfo));
        render("/admin/themes_authorization.tpl");
    }

    public void findByPageForSearch4Member(String select, String sqlExceptSelect){
        Page<Themes> pager = getModel(getModelClass()).paginate(getParaToInt("pageNumberMem", 1),
                                                                getParaToInt(PAGE_SIZE, 10), select, sqlExceptSelect);
        setAttr("memberPage", pager);
    }

    public void findByPageForSearch4City(String select, String sqlExceptSelect){
        Page<Themes> pager = getModel(getModelClass()).paginate(getParaToInt("pageNumberCity", 1),
                                                                getParaToInt(PAGE_SIZE, 10), select, sqlExceptSelect);
        setAttr("cityPage", pager);
    }

    private String getTypeText(int value){
        switch(value){
            case 0:
                return "外链";
            case 1:
                return "开户";
            case 2:
                return "充值缴费";
            case 3:
                return "实名补登记";
            case 5:
                return "政企专区";
            default:
                return "未知类型";

        }

    }
}
